package se.webbzon.boltzmann.menu;

import java.awt.image.ImageObserver;

import se.webbzon.boltzmann.configuration.Controls;
import se.webbzon.boltzmann.input.Input;

public class ControlPage extends MFlowPage {
	
	// The layout of this page
	private final AbstractGameMenuLayout layout;
	
	// The radio group for the input
	private final ControlGroup group;

	/*============================================================
	Constructors
	============================================================*/
	
	public ControlPage(ImageObserver observer, AbstractGameMenuLayout layout, MPage parent) {
		super(observer,layout.getPageLayout(),parent,"Controls");
		this.layout = layout;
		group = new ControlGroup();
		
		addItem(new PageLabel(observer, layout.getLabelLayout(),this));
		addRow(0.25);
		addItem(new ReturnButton(getImageObserver(),layout.getButtonLayout(), parent));
		addRow();
		addItem(new ApplyButton(layout.getButtonLayout()));
		addItem(new EditButton(layout.getButtonLayout()));
		addRow();
		Controls controls = Controls.instance();
		for (int i = 0; i < controls.inputs(); i++) {
			Input input = controls.getInput(i);
			addItem(new ControlRadio(layout.getButtonLayout(),input));
			addRow(0.25);
		}
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void onEnter(GameMenu menu) {}

	@Override public void onLeave(GameMenu menu) {}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	private final class ApplyButton extends MButton {

		public ApplyButton(ButtonLayout layout) {
			super(getImageObserver(), layout, false, "Apply");
		}

		@Override public void onClick(GameMenu menu) {
			Object input = group.getValue();
			if (input instanceof Input) {
				Input i = (Input) input;
				Controls.instance().setInput(i);
				menu.getGameConfiguration().getPlayer(0).setInput(i);
			}
		}
		
	}
	
	private final class EditButton extends MButton {

		public EditButton(ButtonLayout layout) {
			super(getImageObserver(), layout, false, "Edit");
		}

		@Override public void onClick(GameMenu menu) {
			menu.setPage(new ControlEditPage(getImageObserver(), layout,ControlPage.this));
		}
		
	}
	
	private final class ControlGroup extends MRadioGroup {

		public ControlGroup() {
			super(Controls.instance().getInput());
		}

		@Override public void onChangeValue(Object value) {}
		
	}
	
	private final class ControlRadio extends MRadio {

		public ControlRadio(ButtonLayout layout, Input input) {
			super(getImageObserver(), layout, group, input, true, input.getName());
		}
		
	}

}
